<?php


/**
 * 获取活动列表
 *
 * @access  public
 *
 * @return void
 */
function get_sql_package_list(){
	
	/* 查询条件 */
	$filter['keywords']   		= 	empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
	if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1){
		$filter['keywords'] 	= 	$filter['keywords'];
	}
	$filter['sort_by']    		= 	empty($_REQUEST['sort_by']) ? 'act_id' : trim($_REQUEST['sort_by']);
	$filter['sort_order'] 		= 	empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

	$where 						= 	(!empty($filter['keywords'])) ? " AND act_name like '%". Utils::mysql_like_quote($filter['keywords']) ."%'" : '';
   
	/* 获活动数据 */
	$sql = "SELECT act_id, act_name AS package_name, start_time, end_time, is_finished, ext_info ".
		   " FROM " . 'ybr_goods_activity' .
		   " WHERE act_type = " . GAT_PACKAGE . $where .
		   " ORDER by $filter[sort_by] $filter[sort_order] ";

    return $sql;
}

/**
 * 取得商品列表：用于把商品添加到组合、关联类、赠品类
 * @param   object  $filters    过滤条件
 */
function get_goods_list($filter){
    $filter['keyword'] 		= 	$filter['keyword'];
    $where 					= 	get_where_sql($filter); // 取得过滤条件

    /* 取得数据 */
    $sql 					= 	'SELECT goods_id, goods_name, shop_price '.
           						'FROM ' . 'ybr_goods' . ' AS g ' . $where .
           						'LIMIT 50';
    $row				 	= 	M()->query($sql);

    return $row;
}

/**
 * 生成过滤条件：用于 get_goodslist 和 get_goods_list
 * @param   object  $filter
 * @return  string
 */
function get_where_sql($filter){
    $time 		= 	date('Y-m-d');

    $where  	= 	isset($filter['is_delete']) && $filter['is_delete'] == '1' ?' WHERE is_delete = 1 ' : ' WHERE is_delete = 0 ';
    $where 		.= 	(isset($filter['real_goods']) && ($filter['real_goods'] > -1)) ? ' AND is_real = ' . intval($filter['real_goods']) : '';
    $where 		.= 	isset($filter['cat_id']) && $filter['cat_id'] > 0 ? ' AND ' . get_children($filter['cat_id']) : '';
    $where 		.= 	isset($filter['brand_id']) && $filter['brand_id'] > 0 ? " AND brand_id = '" . $filter['brand_id'] . "'" : '';
    $where 		.=	isset($filter['intro_type']) && $filter['intro_type'] != '0' ? ' AND ' . $filter['intro_type'] . " = '1'" : '';
    $where 		.= 	isset($filter['intro_type']) && $filter['intro_type'] == 'is_promote' ?
        			" AND promote_start_date <= '$time' AND promote_end_date >= '$time' " : '';
    $where 		.= 	isset($filter['keyword']) && trim($filter['keyword']) != '' ?
        			" AND (goods_name LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%' OR goods_sn LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%' OR goods_id LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%') " : '';
    $where 		.= 	isset($filter['suppliers_id']) && trim($filter['suppliers_id']) != '' ?
        			" AND (suppliers_id = '" . $filter['suppliers_id'] . "') " : '';

    $where 		.= 	isset($filter['in_ids']) ? ' AND goods_id ' . db_create_in($filter['in_ids']) : '';
    $where 		.=	isset($filter['exclude']) ? ' AND goods_id NOT ' . db_create_in($filter['exclude']) : '';
    $where 		.= 	isset($filter['stock_warning']) ? ' AND goods_number <= warn_number' : '';
    return $where;
}



/**
 * 取商品的货品列表
 *
 * @param       mixed       $goods_id       单个商品id；多个商品id数组；以逗号分隔商品id字符串
 * @param       string      $conditions     sql条件
 *
 * @return  array
 */
function get_good_products($goods_id, $conditions = ''){
    if (empty($goods_id)){
        return array();
    }

    switch (gettype($goods_id)){
        case 'integer':
            $_goods_id 		= 	"goods_id = '" . intval($goods_id) . "'";

        break;

        case 'string':
        case 'array':

            $_goods_id 		= 	db_create_in($goods_id, 'goods_id');

        break;
    }

    /* 取货品 */
    $sql 					= 	"SELECT * FROM " . 'ybr_products' . " WHERE $_goods_id $conditions";
    $result_products 		= 	M()->query($sql);

    /* 取商品属性 */
    $sql 					= 	"SELECT goods_attr_id, attr_value FROM " . 'ybr_goods_attr' . " WHERE $_goods_id";
    $result_goods_attr 		= 	M()->query($sql);

    $_goods_attr 			= 	array();
    foreach ($result_goods_attr as $value){
        $_goods_attr[$value['goods_attr_id']] 	= 	$value['attr_value'];
    }

    /* 过滤货品 */
    foreach ($result_products as $key => $value){
        $goods_attr_array = explode('|', $value['goods_attr']);
        if (is_array($goods_attr_array)){
            $goods_attr 		= 	array();
            foreach ($goods_attr_array as $_attr){
                $goods_attr[] 	= 	$_goods_attr[$_attr];
            }

            $goods_attr_str 	= 	implode('，', $goods_attr);
        }

        $result_products[$key]['goods_attr_str'] = $goods_attr_str;
    }

    return $result_products;
}

/**
 * 取得品牌列表
 * @return array 品牌列表 id => name
 */
function get_brand_list(){
    $sql 		= 	'SELECT brand_id, brand_name FROM ' . 'ybr_brand' . ' ORDER BY sort_order';
    $res 		= 	M()->query($sql);

    $brand_list = 	array();
    foreach ($res AS $row){
        $brand_list[$row['brand_id']] = addslashes($row['brand_name']);
    }
    return $brand_list;
}


/**
 * 保存某礼包的商品
 * @param   int     $package_id
 * @return  void
 */
function handle_packagep_goods($package_id){
    $sql 		= 	"UPDATE " . 'ybr_package_goods' . " SET " .
            		" package_id = '$package_id' " .
            		" WHERE package_id = '0'" .
            		" AND admin_id = '$_SESSION[admin_id]'";
    M()->query($sql);
}


/**
 *  将一个用户自定义时区的日期转为GMT时间戳
 *
 * @access  public
 * @param   string      $str
 *
 * @return  integer
 */
function local_strtotime($str){
    //$timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

    /**
    * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600)
    * 先用mktime生成时间戳，再减去date('Z')转换为GMT时间，然后修正为用户自定义时间。以下是化简后结果
    **/
    //$time = strtotime($str) - $timezone * 3600;
    $time = strtotime($str);
    return $time;

}


/**
 * 获取指定id package 的信息
 *
 * @access  public
 * @param   int         $id         package_id
 *
 * @return array       array(package_id, package_name, goods_id,start_time, end_time, min_price, integral)
 */
function get_package_info($id){
	
	$CommonModel		=	new CommonModel();
	
    $id 				= 	is_numeric($id)?intval($id):0;
    $now 				= 	gmtime();

    $sql 				= 	"SELECT act_id AS id,  act_name AS package_name, goods_id , goods_name, start_time, end_time, act_desc, ext_info".
           					" FROM " . 'ybr_goods_activity' .
           					" WHERE act_id='$id' AND act_type = " . GAT_PACKAGE;

    $package 			= 	$CommonModel->GetRow($sql);

    /* 将时间转成可阅读格式 */
    if ($package['start_time'] <= $now && $package['end_time'] >= $now){
        $package['is_on_sale'] 	= 	"1";
    }
    else{
        $package['is_on_sale'] 	= 	"0";
    }
    $package['start_time'] 		= 	local_date('Y-m-d H:i', $package['start_time']);
    $package['end_time']   		= 	local_date('Y-m-d H:i', $package['end_time']);
    $row 						= 	unserialize($package['ext_info']);
    unset($package['ext_info']);
    if ($row){
        foreach ($row as $key=>$val){
            $package[$key] = $val;
        }
    }

    $sql 				= 	"SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, ".
           					" g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, g.is_real, ".
           					" IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price " .
           					" FROM " . 'ybr_package_goods' . " AS pg ".
           					"   LEFT JOIN ". 'ybr_goods' . " AS g ".
           					"   ON g.goods_id = pg.goods_id ".
           					" LEFT JOIN " . 'ybr_member_price' . " AS mp ".
                			"ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
           					" WHERE pg.package_id = " . $id. " ".
           					" ORDER BY pg.package_id, pg.goods_id";

    $goods_res 			= 	$CommonModel->query($sql);

    $market_price       = 	0;
    $real_goods_count   = 	0;
    $virtual_goods_count= 	0;

    foreach($goods_res as $key => $val){
        $goods_res[$key]['goods_thumb']         	= 	get_image_path($val['goods_id'], $val['goods_thumb'], true);
        $goods_res[$key]['market_price_format'] 	= 	price_format($val['market_price']);
        $goods_res[$key]['rank_price_format']   	= 	price_format($val['rank_price']);
        $market_price 								+= 	$val['market_price'] * $val['goods_number'];
        /* 统计实体商品和虚拟商品的个数 */
        if ($val['is_real']){
            $real_goods_count++;
        }
        else{
            $virtual_goods_count++;
        }
    }

    if ($real_goods_count > 0){
        $package['is_real']            	= 	1;
    }
    else{
        $package['is_real']            	= 	0;
    }

    $package['goods_list']            	= 	$goods_res;
    $package['market_package']        	= 	$market_price;
    $package['market_package_format'] 	= 	price_format($market_price);
    $package['package_price_format']  	= 	price_format($package['package_price']);

    return $package;
}

/**
 * 重新获得商品图片与商品相册的地址
 *
 * @param int $goods_id 商品ID
 * @param string $image 原商品相册图片地址
 * @param boolean $thumb 是否为缩略图
 * @param string $call 调用方法(商品图片还是商品相册)
 * @param boolean $del 是否删除图片
 *
 * @return string   $url
 */
function get_image_path($goods_id, $image='', $thumb=false, $call='goods', $del=false){
    $url 		= 	empty($image) ? $GLOBALS['_CFG']['no_picture'] : $image;
    return $url;
}







